package cc.fs.zhihuapp.ui.receivers;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

/**
 * 使用ContentObserver监听数据库截取收到的短信,填写验证码（没有做深刻的测试 有可能数据库本身变化引发操作需要详细测试）
 */
public class SmsContent extends ContentObserver {

    private static SmsContent instance;
    private Context context;
    private SmsCallback smsCallback;

    public SmsContent(Context context, Handler handler,SmsCallback smsCallback) {
        super(handler);
        this.context = context;
        this.smsCallback = smsCallback;
    }

    /**
     * 注册监控短信调用一次即可
     */
    public static void register(Context context,SmsCallback smscallback) {
        if (instance == null) {
            instance = new SmsContent(context, new Handler(),smscallback);
        }
        context.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, instance);
    }

    /**
     * 取消注册监控短信
     */
    public static void unregister(Context context) {
        if (instance == null) {
            return;
        }
        context.getContentResolver().unregisterContentObserver(instance);
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(Uri.parse("content://sms/inbox"),
                    new String[]{"*"},
                    "_id>?",
                    new String[]{"-1"},
                    "date desc");//倒序，也就是最新的在第一条
            if (cursor != null) {
                if (cursor.moveToNext()) {
                    String body = cursor.getString(cursor.getColumnIndex("body"));
                    String _id = cursor.getString(cursor.getColumnIndex("_id"));
                    final String address = cursor.getString(cursor.getColumnIndex("address"));
                    Log.e("----", "拦截到短信：body=" + body + ";_id=" + _id + ";address=" + address);
                    if(smsCallback != null)
                        smsCallback.run(body);
                }
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void onChange(boolean selfChange, Uri uri) {
        super.onChange(selfChange, uri);
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri,
                    new String[]{"*"},
                    "_id>?",
                    new String[]{"-1"},
                    "date desc");
            if (cursor != null) {
                if (cursor.moveToNext()) {
                    String body = cursor.getString(cursor.getColumnIndex("body"));
                    String _id = cursor.getString(cursor.getColumnIndex("_id"));
                    final String address = cursor.getString(cursor.getColumnIndex("address"));
                    Log.e("    ", "拦截到短信：body=" + body + ";_id=" + _id + ";address=" + address);
                    if(smsCallback != null)
                        smsCallback.run(body);
                }
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
    }

    public interface SmsCallback {
        void run(String msg);
    }
}
